<?php
/**
 * 兑换码API端点测试脚本
 */

require_once __DIR__ . '/vendor/autoload.php';

use think\facade\Db;
use app\common\model\RedemptionCode;
use app\common\model\RedemptionCodeBatch;
use app\api\controller\RedemptionCode as RedemptionCodeController;

try {
    echo "=== 兑换码API端点测试 ===\n\n";
    
    // 创建测试数据
    echo "1. 准备测试数据\n";
    
    // 创建测试批次
    $batch = new RedemptionCodeBatch();
    $batchId = $batch->insertGetId([
        'title' => 'API测试批次',
        'description' => 'API端点测试用批次',
        'total_count' => 3,
        'code_length' => 8,
        'code_prefix' => 'API',
        'discount_amount' => 50.00,
        'discount_percent' => 0,
        'max_uses_per_code' => 1,
        'start_time' => time(),
        'end_time' => time() + 86400 * 30,
        'admin_id' => 1,
        'status' => RedemptionCodeBatch::STATUS_ACTIVE,
        'create_time' => time(),
        'update_time' => time(),
    ]);
    
    // 生成测试兑换码
    $codes = $batch->generateRedemptionCodes($batchId, 3, 'API', 8);
    echo "✓ 创建测试批次和兑换码: " . implode(', ', $codes) . "\n";
    
    // 测试2: verify API
    echo "\n2. 测试 verify API\n";
    
    $controller = new RedemptionCodeController();
    
    // 测试有效兑换码验证
    $_POST['code'] = $codes[0];
    $result = $controller->verify();
    $data = json_decode($result->getContent(), true);
    
    if ($data['code'] === 1) {
        echo "✓ 有效兑换码验证成功\n";
        echo "  - 兑换码: {$data['data']['code']}\n";
        echo "  - 折扣金额: {$data['data']['discount_amount']}\n";
        echo "  - 状态: {$data['data']['status']}\n";
    } else {
        echo "✗ 有效兑换码验证失败: {$data['msg']}\n";
    }
    
    // 测试无效兑换码验证
    $_POST['code'] = 'INVALID123';
    $result = $controller->verify();
    $data = json_decode($result->getContent(), true);
    
    if ($data['code'] === 0) {
        echo "✓ 无效兑换码正确返回错误: {$data['msg']}\n";
    } else {
        echo "✗ 无效兑换码验证异常\n";
    }
    
    // 测试3: batchVerify API
    echo "\n3. 测试 batchVerify API\n";
    
    $_POST['codes'] = json_encode([$codes[0], $codes[1], 'INVALID123']);
    $result = $controller->batchVerify();
    $data = json_decode($result->getContent(), true);
    
    if ($data['code'] === 1) {
        echo "✓ 批量验证成功\n";
        echo "  - 有效兑换码数量: " . count($data['data']['valid_codes']) . "\n";
        echo "  - 无效兑换码数量: " . count($data['data']['invalid_codes']) . "\n";
        echo "  - 总价值: {$data['data']['total_value']}\n";
    } else {
        echo "✗ 批量验证失败: {$data['msg']}\n";
    }
    
    // 测试4: use API (需要模拟登录用户)
    echo "\n4. 测试 use API\n";
    
    // 模拟用户登录状态
    session_start();
    $_SESSION['user'] = ['id' => 1, 'username' => 'testuser'];
    
    $_POST['code'] = $codes[2];
    $_POST['orderId'] = 12345;
    
    try {
        $result = $controller->use();
        $data = json_decode($result->getContent(), true);
        
        if ($data['code'] === 1) {
            echo "✓ 兑换码使用成功\n";
            echo "  - 消息: {$data['msg']}\n";
        } else {
            echo "✗ 兑换码使用失败: {$data['msg']}\n";
        }
    } catch (Exception $e) {
        echo "✗ 兑换码使用异常: " . $e->getMessage() . "\n";
    }
    
    // 测试5: history API
    echo "\n5. 测试 history API\n";
    
    try {
        $result = $controller->history();
        $data = json_decode($result->getContent(), true);
        
        if ($data['code'] === 1) {
            echo "✓ 历史记录查询成功\n";
            echo "  - 记录数量: " . count($data['data']['list']) . "\n";
        } else {
            echo "✗ 历史记录查询失败: {$data['msg']}\n";
        }
    } catch (Exception $e) {
        echo "✗ 历史记录查询异常: " . $e->getMessage() . "\n";
    }
    
    // 测试6: 错误处理测试
    echo "\n6. 测试错误处理\n";
    
    // 测试空参数
    unset($_POST['code']);
    $result = $controller->verify();
    $data = json_decode($result->getContent(), true);
    
    if ($data['code'] === 0) {
        echo "✓ 空参数错误处理正确: {$data['msg']}\n";
    } else {
        echo "✗ 空参数错误处理异常\n";
    }
    
    // 测试过期兑换码
    $expiredCode = RedemptionCode::create([
        'batch_id' => $batchId,
        'code' => 'EXPIRED123',
        'title' => 'API测试批次',
        'description' => 'API端点测试用批次',
        'type' => 'single',
        'discount_amount' => 50.00,
        'discount_percent' => 0,
        'max_uses' => 1,
        'used_count' => 0,
        'start_time' => time() - 86400 * 2,
        'end_time' => time() - 86400, // 昨天过期
        'status' => RedemptionCode::STATUS_ACTIVE,
        'admin_id' => 1,
        'create_time' => time(),
        'update_time' => time(),
    ]);
    
    $_POST['code'] = 'EXPIRED123';
    $result = $controller->verify();
    $data = json_decode($result->getContent(), true);
    
    if ($data['code'] === 0 && strpos($data['msg'], '过期') !== false) {
        echo "✓ 过期兑换码错误处理正确: {$data['msg']}\n";
    } else {
        echo "✗ 过期兑换码错误处理异常\n";
    }
    
    echo "\n=== API端点测试完成 ===\n";
    
} catch (Exception $e) {
    echo "测试过程中发生错误: " . $e->getMessage() . "\n";
    echo "错误文件: " . $e->getFile() . "\n";
    echo "错误行号: " . $e->getLine() . "\n";
} finally {
    // 清理测试数据
    echo "\n清理测试数据...\n";
    
    try {
        // 删除测试兑换码
        Db::name('redemption_code')->where('batch_id', $batchId)->delete();
        Db::name('redemption_code')->where('code', 'EXPIRED123')->delete();
        
        // 删除测试批次
        Db::name('redemption_code_batch')->where('id', $batchId)->delete();
        
        // 删除使用记录
        Db::name('redemption_code_usage')->where('code', 'like', 'API%')->delete();
        Db::name('redemption_code_usage')->where('code', 'EXPIRED123')->delete();
        
        echo "✓ 测试数据清理完成\n";
    } catch (Exception $e) {
        echo "✗ 清理测试数据失败: " . $e->getMessage() . "\n";
    }
}